﻿Imports System.Text
Imports System.Security.Cryptography
Imports System.ComponentModel
Imports System.IO
Imports System.Net
Imports System.Net.WebProxy
Imports System.Globalization

Public Class upfile

    Private pProxy As String = Nothing
    Private pTimeOut As Integer = 3000
    Private pUrl As String = Nothing
    Private pUPL_item As RegularExpressions.MatchCollection
    Private Info As String
    Private pexe_path As String
    Private pmodules_path As String
    Private phost_link As String
    Private pupldownload_api As String


    Private WithEvents UPL_List As New BackgroundWorker
    Private WithEvents DownloadUPL As New BackgroundWorker
    Private HttpWebRequest As HttpWebRequest
    Private HttpWebResponse As HttpWebResponse
    Private HttpWebResponseStream As Stream



    Property proxy As String
        Get
            Return pProxy
        End Get
        Set(ByVal value As String)
            pProxy = value
        End Set
    End Property

    Property TimeOut As Integer
        Get
            Return pTimeOut
        End Get
        Set(ByVal value As Integer)
            IIf(pTimeOut >= 3000, pTimeOut = TimeOut, pTimeOut = 3000)
        End Set
    End Property

    Property URL As String
        Get
            Return pUrl
        End Get
        Set(ByVal value As String)
            pUrl = value
        End Set
    End Property

    Property exe_path As String
        Get
            Return pexe_path
        End Get
        Set(ByVal value As String)
            pexe_path = value
        End Set
    End Property

    Property modules_path As String
        Get
            Return pmodules_path
        End Get
        Set(ByVal value As String)
            pmodules_path = value
        End Set
    End Property

    Property host_link As String
        Get
            Return phost_link
        End Get
        Set(ByVal value As String)
            phost_link = value
        End Set
    End Property

    Property upldownload_api As String
        Get
            Return pupldownload_api
        End Get
        Set(ByVal value As String)
            pupldownload_api = value
        End Set
    End Property
    ReadOnly Property UPL_item As RegularExpressions.MatchCollection
        Get
            Return pUPL_item
        End Get

    End Property

    Private Function ToBig5(ByVal str As String) As String


        Dim inputstr As String = ""
        Dim r As String = ""
        Dim mc As RegularExpressions.MatchCollection = RegularExpressions.Regex.Matches(str, "\\u([\w]{2})([\w]{2})", RegularExpressions.RegexOptions.Compiled Or RegularExpressions.RegexOptions.IgnoreCase)

        If mc.Count > 0 Then

            Dim bts As Byte() = New Byte(1) {}
            For Each m As RegularExpressions.Match In mc
                'MsgBox(m.Groups(1).Value)
                inputstr += m.Groups(0).Value
                bts(0) = CByte(Integer.Parse(m.Groups(2).Value, NumberStyles.HexNumber))
                bts(1) = CByte(Integer.Parse(m.Groups(1).Value, NumberStyles.HexNumber))
                r += Encoding.Unicode.GetString(bts)
            Next
            r = str.Replace(inputstr, r)

            Return r
        Else
            Return str
        End If

    End Function

    Private Function HTML(ByVal url As String) As String
        Dim myRequest As System.Net.HttpWebRequest = System.Net.WebRequest.Create(url)
        Dim Return_HTML As String = ""
        Dim myResponse As System.Net.WebResponse = Nothing
        Dim myStream As IO.Stream = Nothing
        Dim streamReader As IO.StreamReader = Nothing
        Try
            myRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; fdnet; .NET4.0E)"
            myRequest.ContentType = "application/x-www-form-urlencoded"
            myRequest.Timeout = pTimeOut
            myRequest.KeepAlive = False
            myResponse = myRequest.GetResponse
            myStream = myResponse.GetResponseStream
            streamReader = New IO.StreamReader(myStream, System.Text.Encoding.UTF8)
            Return_HTML = streamReader.ReadToEnd


            'myStream.Dispose()
            'streamReader.Dispose()

            Return Return_HTML
        Catch ex As Exception
            Return "error"
        Finally
            If Not streamReader Is Nothing Then
                streamReader.Close()
                streamReader.Dispose()
            End If
            If Not myResponse Is Nothing Then
                myResponse.Close()
            End If
            If Not myStream Is Nothing Then
                myStream.Close()
                myStream.Dispose()

            End If

        End Try

    End Function
    Private Function Regular(ByVal InputSTR As String, ByVal RegularSTR As String) As RegularExpressions.MatchCollection
        Try
            Dim reg As New System.Text.RegularExpressions.Regex(RegularSTR)
            Return reg.Matches(InputSTR)
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

    Private Function UplScriptList(ByVal Path As String) As String
        Dim value As String = ""
        Dim a As String = ""
        Dim MySF As IO.StreamReader = New IO.StreamReader(Path, System.Text.Encoding.Default)
        value = MySF.ReadToEnd() '讀取全部會包含換行符號 

        MySF.Close()
        Return value


    End Function

    Private Function UplScript(ByVal URL As String) As RegularExpressions.MatchCollection
        Info = HTML(URL)
        Dim UplList As RegularExpressions.MatchCollection
   
        If Info <> "error" Then

            UplList = Regular(Info, "{([^,]+),([^,]+),([^,]+),([^,]+)}")
            Return UplList
        Else

            Return Nothing

        End If




    End Function

    Private Sub SaveFile(ByVal strPathName As String, ByVal strContent As String, ByVal Method As Boolean)

        Try
            Dim swWriter As IO.StreamWriter = New IO.StreamWriter(strPathName, Method, System.Text.Encoding.Default)
            swWriter.Write(strContent)
            swWriter.Close()
        Catch ex As Exception : End Try

    End Sub

    Private Sub UpFileLog(ByVal FilePath As String)
        If IO.File.Exists(FilePath) = False Then
            Dim FS As IO.FileStream
            FS = New IO.FileStream(FilePath, IO.FileMode.Create)
            FS.Flush()
            FS.Close()

        End If

    End Sub

   

    Private Function DownloadUPLSctip(ByVal URL As String, ByVal Path As String) As Boolean

        Dim DownloadByte As Long = 32
        Dim byteBuffer() As Byte = New Byte(32) {}
        Dim bytesRead As Integer
        Dim lFileStream As FileStream
        System.Net.ServicePointManager.DefaultConnectionLimit = 200
        System.Net.ServicePointManager.Expect100Continue = False
        GC.Collect()
        HttpWebRequest = WebRequest.Create(URL)
        HttpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"
        'HttpWebRequest.Proxy = Nothing
        If proxy = Nothing Then
            HttpWebRequest.Proxy = Nothing
        Else
            HttpWebRequest.Proxy = New WebProxy(proxy)
        End If

        HttpWebRequest.KeepAlive = False
        HttpWebRequest.Timeout = 10000
        HttpWebResponse = HttpWebRequest.GetResponse
        HttpWebResponseStream = HttpWebRequest.GetResponse().GetResponseStream()
        lFileStream = New FileStream(Path, FileMode.Create)
        Try
            Do

                bytesRead = HttpWebResponseStream.Read(byteBuffer, 0, DownloadByte)
                lFileStream.Write(byteBuffer, 0, bytesRead)

            Loop While bytesRead > 0
            HttpWebRequest.Abort()
            HttpWebResponse.Close()
            HttpWebResponseStream.Close()
            lFileStream.Close()
            HttpWebResponseStream.Dispose()
            lFileStream.Dispose()

            Return True
        Catch ex As Exception
            HttpWebRequest.Abort()
            HttpWebResponse.Close()
            HttpWebResponseStream.Close()
            lFileStream.Close()
            HttpWebResponseStream.Dispose()
            lFileStream.Dispose()
            Return False
        Finally
            HttpWebRequest.Abort()
            HttpWebResponse.Close()
            HttpWebResponseStream.Close()
            lFileStream.Close()
            HttpWebResponseStream.Dispose()
            lFileStream.Dispose()
            GC.Collect()
        End Try

    End Function
    Private Sub UPL_List_Worker(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles UPL_List.DoWork

        UpFileLog(System.Environment.CurrentDirectory + "\UpFileLog.txt")
        Dim UplLists As RegularExpressions.MatchCollection = UplScript(pUrl)



        UPL_List.ReportProgress(0, UplLists)
    End Sub



    Private Sub UPL_List_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles UPL_List.ProgressChanged
        Dim uplName As String = Nothing
        Dim uplpatch As String = Nothing
        Dim uplauthor As String = Nothing
        Dim uplNote As String = Nothing


        If e.ProgressPercentage = 0 Then
            pUPL_item = e.UserState
            Dim List As String = UplScriptList(System.Environment.CurrentDirectory + "\UpFileLog.txt")
            If Not pUPL_item Is Nothing Then
                For i As Integer = 0 To pUPL_item.Count - 1
                    If List.IndexOf(pUPL_item.Item(i).Groups(1).ToString + "," + pUPL_item.Item(i).Groups(2).ToString + "," + pUPL_item.Item(i).Groups(3).ToString) < 0 Then
                        Dim itmx As New ListViewItem
                        uplName = Regular(pUPL_item.Item(i).Groups(1).ToString, "upl+""" + ":" + """" + "([^" + """" + "]+)").Item(0).Groups(1).ToString
                        uplpatch = Regular(pUPL_item.Item(i).Groups(2).ToString, "patch+""" + ":" + """" + "([^" + """" + "]+)").Item(0).Groups(1).ToString
                        uplauthor = Regular(pUPL_item.Item(i).Groups(3).ToString, "author+""" + ":" + """" + "([^" + """" + "]+)").Item(0).Groups(1).ToString
                        uplNote = Regular(pUPL_item.Item(i).Groups(4).ToString, "note+""" + ":" + """" + "([^" + """" + "]+)").Item(0).Groups(1).ToString

                        itmx = Form1.ListView1.Items.Add(ToBig5(uplName))
                        itmx.SubItems.Add(ToBig5(uplauthor))
                        itmx.SubItems.Add(ToBig5(uplpatch))
                        itmx.SubItems.Add(ToBig5(uplNote))
                    End If


                Next
            End If
            Form1.ToolStripStatusLabel1.Text = "目前有" & Form1.ListView1.Items.Count & "個腳本等待更新"
            If Form1.ListView1.Items.Count > 0 Then
                Form1.Visible = True
            Else
                Shell(pexe_path, vbNormalFocus)
                Form1.Close()
            End If

        End If
    End Sub

    Private Sub DownloadUPL_Worker(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles DownloadUPL.DoWork
        Try
            Dim uplName As String = Nothing
            Dim uplpatch As String = Nothing
          
            Dim Num As Integer = 1
            For i As Integer = 0 To pUPL_item.Count - 1
                Dim List As String = UplScriptList(System.Environment.CurrentDirectory + "\UpFileLog.txt")
                If Not pUPL_item Is Nothing Then
                    If List.IndexOf(pUPL_item.Item(i).Groups(1).ToString + "," + pUPL_item.Item(i).Groups(2).ToString + "," + pUPL_item.Item(i).Groups(3).ToString) < 0 Then
                        uplName = Regular(pUPL_item.Item(i).Groups(1).ToString, "upl+""" + ":" + """" + "([^" + """" + "]+)").Item(0).Groups(1).ToString
                        uplpatch = Regular(pUPL_item.Item(i).Groups(2).ToString, "patch+""" + ":" + """" + "([^" + """" + "]+)").Item(0).Groups(1).ToString
                       

                        'DownloadUPLSctip(pUPL_item.Item(i).Groups(5).ToString, pmodules_path + "\" + pUPL_item.Item(i).Groups(1).ToString)
                        'MsgBox(pupldownload_api + "&upl=" + uplName + "&patch=" + uplpatch)
                        DownloadUPLSctip(pupldownload_api + "&upl=" + ToBig5(uplName) + "&patch=" + ToBig5(uplpatch), pmodules_path + "\" + ToBig5(uplName) + ".upl")
                        DownloadUPL.ReportProgress(0, Num)
                        Num = Num + 1
                    End If
                End If
            Next
            SaveFile(System.Environment.CurrentDirectory + "\UpFileLog.txt", Info, False)
            DownloadUPL.ReportProgress(1)




        Catch ex As Exception

        End Try
    

    End Sub



    Private Sub DownloadUPL_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles DownloadUPL.ProgressChanged
        If e.ProgressPercentage = 0 Then
            Form1.ToolStripStatusLabel1.Text = "目前更新......(" & Form1.ListView1.Items.Count & "/" & e.UserState & ")"
        ElseIf e.ProgressPercentage = 1 Then
            MsgBox("成功更新", MsgBoxStyle.Information, "訊息")
            Shell(pexe_path, vbNormalFocus)
            Form1.Close()
        End If

    End Sub

    Public Sub Start()
        Try
            UPL_List.WorkerReportsProgress = True
            UPL_List.WorkerSupportsCancellation = True
            UPL_List.RunWorkerAsync()
        Catch ex As Exception : End Try

    End Sub
    Public Sub Download()
        Try
            DownloadUPL.WorkerReportsProgress = True
            DownloadUPL.WorkerSupportsCancellation = True
            DownloadUPL.RunWorkerAsync()
        Catch ex As Exception : End Try

    End Sub
End Class
